//
//  SignCheckoutViewController.m
//  GYMWinners
//
//  Created by Logic Solutions on 3/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SignCheckoutViewController.h"
#import "FormatHelper.h"
#import "MapKit/MapKit.h"
#import "SignViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"


@implementation SignCheckoutViewController

@synthesize locationManager;
@synthesize countdownLabel;
@synthesize timer;
@synthesize timeConsumed;
@synthesize anno_lat;
@synthesize anno_lon;
@synthesize checkInID;

static NSInteger oneMinute=60; //one minute= 60 seconds 
static NSInteger oneHour=3600; //one hour= 3600 seconds

static NSInteger CheckedInStat = 0;

-(void)checkInNow{
    
    if (timeConsumed!=0) {
        timeConsumed=0;
    }
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

-(IBAction)checkOutNow{
    
    [self.timer invalidate];
    NSLog(@"-----timeConsumed=%d",timeConsumed);
    
    if( timeConsumed > 3 )
    {
        NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
        [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
        [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lat] forKey:@"lat"];
        [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lon] forKey:@"lon"];
        [slist setObject:checkInID forKey:@"customerCheckinId"];
        [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/checkin/end"]; 
    }
    else
    {
        [[BaseroutAPI sharedInstance] MessageBox:@"训练取消" Message:@"下次请打开定位服务，并至少训料30分钟再离开"];
        
        [[self navigationController] popToRootViewControllerAnimated:YES];
    }
    
}

-(void) onTimer{
    
    timeConsumed++;    
    
    NSInteger hourPart=timeConsumed/oneHour;
    NSInteger minLeft=timeConsumed%oneHour;
    
    NSInteger minPart=minLeft/oneMinute;
    NSInteger secPart=minLeft%oneMinute;
    
    if (timeConsumed > 0) {
        
        NSString* strHour=[FormatHelper initFormatHHMMSS:hourPart];
        NSString* strMin=[FormatHelper initFormatHHMMSS:minPart];
        NSString* strSec=[FormatHelper initFormatHHMMSS:secPart];       
        
        countdownLabel.text=[NSString stringWithFormat:@"%@:%@:%@",strHour,strMin,strSec];    
    }
    
//    if (timeConsumed > 0 && (timeConsumed % 5) == 0) {
//        
//        NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
//        [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
//        [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lat] forKey:@"lat"];
//        [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lon] forKey:@"lon"];
//        [slist setObject:checkInID forKey:@"customerCheckinId"];
//        [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/checkin/keepalive"];  
//        
//    }
    
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
     NSLog(@"initWithNibName checkout view");
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad checkout view");

    [super viewDidLoad];
    
    checkInID = @"";
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate=self; 
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=100.0f;
    [locationManager startUpdatingLocation];

    CheckedInStat = 0;
    
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lat] forKey:@"lat"];
    [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lon] forKey:@"lon"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/checkin/start"];
    
    NSLog(@"viewDidLoad checkout view1");
    
    timeConsumed=0;
    [self checkInNow];
    
    NSLog(@"viewDidLoad checkout view2");
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc {
    NSLog(@"dealloc signout view");
    locationManager.delegate = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{

    NSString* lat=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.latitude];
    NSString* lng=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.longitude];
    NSString* acc=[[NSString alloc] initWithFormat:@"%g",newLocation.horizontalAccuracy];
    NSLog(@"New location: %@__%@__%@",lat,lng,acc);

    self.anno_lat = newLocation.coordinate.latitude;
    self.anno_lon = newLocation.coordinate.longitude;
    
}

#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   

        if( CheckedInStat == 0 )
        {
            NSDictionary *responseDict = [responseString JSONValue];
            NSString *CheckInID = [NSString stringWithFormat:@"%@", [responseDict objectForKey:@"id"]];
            
            if( [[BaseroutAPI sharedInstance] validateString:CheckInID] )
            {
                NSLog(@"Check in successfully!"); 
                CheckedInStat = 1;
                checkInID = CheckInID;
            }
            else
            {
                //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"训练失败"]; 
                //[[self navigationController] popViewControllerAnimated:YES];
            }
        }
        else
        {
            NSDictionary *responseDic = [responseString JSONValue];
            NSString *isApproved = [[responseDic objectForKey:@"isApproved"] stringValue];
            
            if( [[isApproved lowercaseString] isEqualToString:@"0"] )
            {
                NSLog(@"Workout was done succesfully!");
                
                if( timeConsumed > 10 ){
                    //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"训练成功"]; 
                    
                    //[[self navigationController] popToRootViewControllerAnimated:YES];
                }
            }
            else
            {
                NSLog(@"Workout failed.");
                
                //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"训练失败"]; 
                
                //[[self navigationController] popToRootViewControllerAnimated:YES];
            }
        }
        
    } else {
        NSLog(@"Unexpected error");  
        //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    
}

@end
